package com.example.xyh.serviceImpl;

import com.example.xyh.dao.ILineItemDao;
import com.example.xyh.dto.LineItemDto;
import com.example.xyh.entity.Business;
import com.example.xyh.entity.LineItem;
import com.example.xyh.service.BusinessService;
import com.example.xyh.service.LineItemService;
import jakarta.annotation.Resource;
import lombok.extern.apachecommons.CommonsLog;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@Component
@CommonsLog
public class LineItemServiceImpl implements LineItemService {
    @Resource
    ILineItemDao iLineItemDao;
    @Resource
    BusinessService businessService;
    @Autowired
    protected ModelMapper modelMapper;

    public LineItemServiceImpl(ILineItemDao iLineItemDao) {
        this.iLineItemDao = iLineItemDao;
    }

    @Override
    public List<LineItemDto> getBusinessItemList(Integer business_id) {
        List<LineItem> lineItemList = iLineItemDao.findByBusiness_BusinessId(business_id);
        return lineItemList.stream()
                .map(item -> new LineItemDto(item.getItemId(), item.getItemName(), item.getItemPrice(),
                        item.getBusiness().getBusinessId(), item.getBusiness().getBusinessName()))
                .collect(Collectors.toList());
    }

    @Override
    public LineItemDto addItem(Integer business_id, String item_name, Double item_price) {
        if (!iLineItemDao.existsByBusiness_BusinessIdAndItemName(business_id, item_name)) {
            Business business = businessService.findByBusinessId(business_id);
            if (business != null) {
                LineItem newLineItem = LineItem.builder()
                        .itemName(item_name)
                        .itemPrice(item_price)
                        .business(business)
                        .build();
                iLineItemDao.save(newLineItem);
                return modelMapper.map(newLineItem, LineItemDto.class);

            } else {
                return null;
            }
        }
        return null;
    }

    @Override
    public LineItem findByItemId(Integer item_id) {
        return iLineItemDao.findByItemId(item_id);
    }


}
